package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SkuController {

    @Autowired
    private SkuFeign skuFeign;

    @GetMapping("/list")
    public String search(@RequestParam(required = false) Map<String, String> searchMap, Model model) {
        // 调用微服务查询数据
        Map<String, Object> resultMap = skuFeign.search(searchMap);
        // 搜索的数据结果
        model.addAttribute("resultMap", resultMap);
        // 返回搜索条件
        model.addAttribute("searchMap", searchMap);
        String url = url(searchMap);
        model.addAttribute("url", url);

        // 分页信息
        Page<SkuInfo> page = new Page<>(
                Long.parseLong(resultMap.get("totalPages").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );
        model.addAttribute("page", page);
        return "search";
    }

    private String url(Map<String, String> searchMap) {
        String url = "/search/list?";
        if (searchMap != null && searchMap.size() > 0) {
            // url += "?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                // 如果是排序条件不用拼接
                if (key.equals("sortField") || key.equals("sortRule")) {
                    continue;
                }
                // 如果是翻页的数据则不拼接
                if (key.equals("pageNum")) {
                    continue;
                }
                url = url + key + "=" + value + "&";
            }
        }
        url = url.substring(0, url.length() - 1);
        return url;
    }
}
